package com.destroyer.common.excel.handler;

import com.alibaba.excel.write.handler.AbstractSheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.destroyer.common.excel.ann.DropExcelProperty;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

/**
 * 下拉选项框
 */
@AllArgsConstructor
public class DropdownListSheetWriteHandler extends AbstractSheetWriteHandler {
    /**
     * 开始列
     */
    private int startCol;
    /**
     * 结束列
     */
    private int endCol;
    /**
     * 数据源
     */
    private String[] array;

    public DropdownListSheetWriteHandler(DropExcelProperty property) {
        this.array = property.options();
        this.startCol = property.startCol();
        this.endCol = property.endCol();
    }




    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();

        // 创建下拉列表约束
        DataValidationConstraint constraint = helper.createExplicitListConstraint(array);

        // 设置下拉列表的单元格范围。这里是设置第一列的第2行到第100行为下拉列表
        CellRangeAddressList addressList = new CellRangeAddressList(1, 5000, startCol, endCol);

        // 创建并添加数据有效性对象
        DataValidation validation = helper.createValidation(constraint, addressList);
        validation.setShowErrorBox(true); // 如果用户输入了无效数据，显示错误框
        sheet.addValidationData(validation);
    }
}
